﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Encodings.Web;
using Kugar.Core.ExtMethod;
using Kugar.UI.Web.AdminLTE.Enums;
using Kugar.UI.Web.AdminLTE.Helpers;
using Kugar.UI.Web.AdminLTE.Helpers.FormExtMethod;
using Kugar.UI.Web.AdminLTE.PageControls.PageCommon;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.WebEncoders.Testing;

namespace Kugar.UI.Web.AdminLTE.PageControls.PageForms
{
    public interface IPageForm
    {
        PageForm_CheckedListField AddCheckBoxList();
        PageForm_CustomContainerField AddCustomContainer();
        PageForm_CustomContentField AddCustomContent();
        PageForm_DatetimePickerField AddDatetime();
        PageForm_DatetimeRangePickerField AddDatetimeRange();
        PageForm_FileUploadField AddFileUpload();

        //PageForm_MultiFileUploadField AddMultiFileUpload();

        PageForm_MultiFileUploadField2 AddMultiFileUpload();

        PageForm_ImageUploadField AddImageUpload();

        //PageForm_MultiImageUploadField2 AddMultiImageUploader();

        //[Obsolete("请不要使用该控件,直接使用AddMultiImageUploader")]
        PageForm_MultiImageUploadField2 AddMultiImageUploader();

        PageForm_LabelField AddLabel();
        PageForm_RadioListField AddRadioList();
        PageForm_SelectorField AddSelector();
        PageForm_TextareaField AddTextarea();
        PageForm_TextBoxField AddTextBox();
        PageForm_TextBoxWithButton AddTextBoxWithButton();
        PageForm_ValueRangeField AddValueRange();
        PageForm_CityPicker AddCityPicker();
        PageForm_SummerNote AddSummerNote();
        PageForm_SwitchField AddSwitchButton();
        PageForm_TreeViewSelector AddTreeViewSelector();
        PageForm_ButtonList AddButtonList();
        PageForm_FieldsGroup AddFieldGroup();
        ViewContext ViewContext { get; }
    }

    public class PageForm_Form : ContainerBase, IPageForm
    {
        private string _method = "";
        private bool _isAjax = false;
        private string _formUrl = "";
        private FormEnctype _enctype = FormEnctype.multipart;
        private LinkTargetType _targetType = LinkTargetType.Self;
        private string _updateElementID = "";
        private List<FormButtonConfig> _formButtonList = new List<FormButtonConfig>(2);
        internal int _defaultLabelWidth = 2;
        internal string _defaultControlWidth = "70%";
        private PageCommon_PanelBoxContainer _panel = null;
        private int _oldDefaultLabelWidth = 2;
        private string _oldDefaultControlWidth = "";


        public PageForm_Form(ViewContext viewContext) : base(viewContext)
        {
            this.Css("form-horizontal weui-form_formcontainer layui-form");
        }

        public PageForm_Form Get(string url = "")
        {
            _formUrl = url;
            _method = "GET";

            return this;
        }



        public PageForm_Form Post(string url = "")
        {
            _formUrl = url;
            _method = "Post";

            return this;
        }

        public PageForm_Form Enctype(FormEnctype enctype = FormEnctype.Application_urlencoded)
        {
            _enctype = enctype;

            return this;
        }

        public PageForm_Form Target(LinkTargetType targetType = LinkTargetType.Self)
        {
            _targetType = targetType;

            return this;
        }

        /// <summary>
        /// 设置表单异步刷新,并且更新指定id的元素
        /// </summary>
        /// <param name="elementID">元素ID,如果在modalwindow内,为空或者空字符串时,则为所在modalwindow的ID</param>
        /// <returns></returns>
        public PageForm_Form UpdateElementID(string elementID = "")
        {
            if (string.IsNullOrWhiteSpace(elementID) && base.AdminLTEUI.IsInModal)
            {
                elementID = ViewContext.ViewData.TryGetValue("ModalWindowID", "").ToStringEx();
            }

            if (string.IsNullOrWhiteSpace(elementID))
            {
                throw new ArgumentOutOfRangeException(nameof(elementID));
            }

            _updateElementID = elementID;
            _isAjax = true;

            return this;
        }

        public PageForm_Form DefaultLabelWidth(int labelWidth)
        {
            _defaultLabelWidth = labelWidth;

            return this;
        }

        public PageForm_Form DefaultControlWidth(string controlWidth)
        {
            _defaultControlWidth = controlWidth;

            return this;
        }

        /// <summary>
        /// 将字段设为宽度90%,用于当在ModalWindow窗口的时候,不需要tips,字段控件可以设为全宽,避免太短
        /// </summary>
        /// <returns></returns>
        public PageForm_Form DefaultFieldFullWidth()
        {
            _defaultControlWidth = "90%";

            return this;
        }


        /// <summary>
        /// 在form的外侧套一个panel框
        /// </summary>
        /// <param name="isWithBox"></param>
        /// <returns></returns>
        public PageForm_Form WithBox(bool isWithBox = true)
        {
            _panel = new PageCommon_PanelBoxContainer(ViewContext);

            return this;
        }

        public override void Dispose()
        {
            if (_formButtonList.HasData())
            {
                ViewContext.Writer.WriteLine("<div class=\"form-group webui-form_buttongroup\">");

                ViewContext.Writer.WriteLine(
                    $"<div class=\"col-sm-offset-{_defaultLabelWidth} col-sm-{12 - _defaultLabelWidth}\">");

                foreach (var btn in _formButtonList)
                {
                    btn.Css("btn-" + btn.GetColor.ToStringEx());

                    ViewContext.Writer.WriteLine(
                        $"<button {btn.Attributes} type=\"{btn._type}\" >{btn.GetText}</button>");
                }


                ViewContext.Writer.WriteLine("</div>");

                ViewContext.Writer.WriteLine("</div>");
            }


            ViewContext.Writer.WriteLine("</div> <!--end box-body -->");

            OutForm();

            ViewContext.Writer.WriteLine("<div class=\"clearfix\"></div>");

            ViewContext.Writer.WriteLine($"</{(IsInForm() ? "div" : "form")}>");

            _panel?.Dispose();

            if (_withOuterBorder)
            {
                ViewContext.Writer.WriteLine($"</div> <!-- outer border -->");
            }
        }

        internal override ContainerBase RenderInternal()
        {
            Attributes.MergeAttr("method", _method.ToUpper());
            Attributes.MergeAttr("enctype", Utility.FormEncTypeToStr(_enctype));

            if (_isAjax)
            {
                Attributes.Data("data-ajax", _isAjax.ToStringEx());
            }

            if (!string.IsNullOrWhiteSpace(_formUrl))
            {
                Attributes.MergeAttr("action", _formUrl);
            }
            else
            {
                Attributes.MergeAttr("action", ViewContext.HttpContext.Request.GetDisplayUrl());
            }

            if (!string.IsNullOrWhiteSpace(_updateElementID))
            {
                Attributes.MergeAttr("data-updateelemid", _updateElementID);
            }

            if (_targetType != LinkTargetType.Self)
            {
                Attributes.MergeAttr("target", Utility.LinkTargetToStr(_targetType));
            }

            var isInForm = IsInForm();

            if (!isInForm)
            {
                ViewContext.Writer.WriteLine("<form class=\"fakeform\"></form>");
            }
            else
            {
                Attributes.MergeAttr("data-innerform", "True");
            }

            if (_withOuterBorder)
            {
                ViewContext.Writer.WriteLine($"<div class=\"{_outerBorderCss}\">");
            }

            _panel?.Render();

            ViewContext.Writer.WriteLine($"<{(isInForm ? "div" : "form")} {Attributes}>");

            EnterForm();

            ViewContext.ViewData["DefaultLabelWidth"] = _defaultLabelWidth;
            ViewContext.ViewData["DefaultControlWidth"] = _defaultControlWidth;

            ViewContext.Writer.WriteLine("<div class=\"box-body\">");

            Html.AntiForgeryToken().WriteTo(ViewContext.Writer, HtmlEncoder.Default);


            return this;
        }


        private void EnterForm()
        {
            var count = (int) ViewContext.TempData.TryGetValue("FormCount", 0);



            _oldDefaultLabelWidth = (int) ViewContext.ViewData.TryGetValue("DefaultLabelWidth", 2);
            _oldDefaultControlWidth = (string) ViewContext.ViewData.TryGetValue("DefaultControlWidth", "");

            ViewContext.ViewData["DefaultLabelWidth"] = _defaultLabelWidth;
            ViewContext.ViewData["DefaultControlWidth"] = _defaultControlWidth;

            ViewContext.TempData.AddOrUpdate("FormCount", count + 1);
        }

        private bool IsInForm()
        {
            var count = (int) ViewContext.TempData.TryGetValue("FormCount", 0);

            return count > 0;
        }

        private void OutForm()
        {
            var count = (int) ViewContext.TempData.TryGetValue("FormCount", 0);

            if (count <= 0)
            {
                return;
            }

            ViewContext.TempData.AddOrUpdate("FormCount", count - 1);

            ViewContext.ViewData["DefaultLabelWidth"] = _oldDefaultLabelWidth;
            ViewContext.ViewData["DefaultControlWidth"] = _oldDefaultControlWidth;
        }

        public class FormButtonConfig : ButtonConfigBase
        {
            internal ButtonTypeEnum _type = ButtonTypeEnum.button;

            public FormButtonConfig(ViewContext viewContext) : base(viewContext)
            {
                this.Css("btn");
                this._color = ColorPaletteEnum.success;
            }

            public FormButtonConfig Type(ButtonTypeEnum type)
            {
                _type = type;
                return this;
            }
        }

        #region 添加控件

        public PageForm_CheckedListField AddCheckBoxList()
        {
            return new PageForm_CheckedListField(this, this.ViewContext);
        }

        public PageForm_CustomContainerField AddCustomContainer()
        {
            return new PageForm_CustomContainerField(this, this.ViewContext);
        }

        public PageForm_CustomContentField AddCustomContent()
        {
            return new PageForm_CustomContentField(this, this.ViewContext);
        }

        public PageForm_DatetimePickerField AddDatetime()
        {
            return new PageForm_DatetimePickerField(this, this.ViewContext);
        }

        public PageForm_DatetimeRangePickerField AddDatetimeRange()
        {
            return new PageForm_DatetimeRangePickerField(this, this.ViewContext);
        }

        public PageForm_FileUploadField AddFileUpload()
        {
            return new PageForm_FileUploadField(this, this.ViewContext);
        }

        //public PageForm_MultiFileUploadField AddMultiFileUpload()
        //{
        //    return new PageForm_MultiFileUploadField(this, this.ViewContext);
        //}

        public PageForm_MultiFileUploadField2 AddMultiFileUpload()
        {
            return new PageForm_MultiFileUploadField2(this, this.ViewContext);
        }

        public PageForm_ImageUploadField AddImageUpload()
        {
            return new PageForm_ImageUploadField(this, this.ViewContext);
        }

        public PageForm_MultiImageUploadField2 AddMultiImageUploader()
        {
            return new PageForm_MultiImageUploadField2(this,ViewContext);
        }

        //public PageForm_MultiImageUploadField2 AddMultiImageUpload()
        //{
        //    return new PageForm_MultiImageUploadField(this, this.ViewContext);
        //}

        public PageForm_LabelField AddLabel()
        {
            return new PageForm_LabelField(this, this.ViewContext);
        }

        public PageForm_RadioListField AddRadioList()
        {
            return new PageForm_RadioListField(this, this.ViewContext);
        }

        public PageForm_SelectorField AddSelector()
        {
            return new PageForm_SelectorField(this, this.ViewContext);
        }

        public PageForm_TextareaField AddTextarea()
        {
            return new PageForm_TextareaField(this, this.ViewContext);
        }

        public PageForm_TextBoxField AddTextBox()
        {
            return new PageForm_TextBoxField(this, this.ViewContext);
        }

        public PageForm_TextBoxWithButton AddTextBoxWithButton()
        {
            return new PageForm_TextBoxWithButton(this, this.ViewContext);
        }

        public PageForm_ValueRangeField AddValueRange()
        {
            return new PageForm_ValueRangeField(this, this.ViewContext);
        }

        public PageForm_CityPicker AddCityPicker()
        {
            return new PageForm_CityPicker(this, this.ViewContext);
        }

        public PageForm_SummerNote AddSummerNote()
        {
            return new PageForm_SummerNote(this, this.ViewContext);
        }

        public PageForm_SwitchField AddSwitchButton()
        {
            return new PageForm_SwitchField(this, this.ViewContext);
        }

        public PageForm_TreeViewSelector AddTreeViewSelector()
        {
            return new PageForm_TreeViewSelector(this, this.ViewContext);
        }

        public PageForm_ButtonList AddButtonList() => new PageForm_ButtonList(this, this.ViewContext);

        public PageForm_FieldsGroup AddFieldGroup() => new PageForm_FieldsGroup(this.ViewContext);

        #endregion
    }

    public class EmptyForm:IPageForm
    {
        public EmptyForm(ViewContext viewContext)
        {
            ViewContext = viewContext;
        }

        public PageForm_CheckedListField AddCheckBoxList()
        {
            return new PageForm_CheckedListField(null, this.ViewContext);
        }

        public PageForm_CustomContainerField AddCustomContainer()
        {
            return new PageForm_CustomContainerField(null, this.ViewContext);
        }

        public PageForm_CustomContentField AddCustomContent()
        {
            return new PageForm_CustomContentField(null, this.ViewContext);
        }

        public PageForm_DatetimePickerField AddDatetime()
        {
            return new PageForm_DatetimePickerField(null, this.ViewContext);
        }

        public PageForm_DatetimeRangePickerField AddDatetimeRange()
        {
            return new PageForm_DatetimeRangePickerField(null, this.ViewContext);
        }

        public PageForm_FileUploadField AddFileUpload()
        {
            return new PageForm_FileUploadField(null, this.ViewContext);
        }

        //public PageForm_MultiFileUploadField AddMultiFileUpload()
        //{
        //    return new PageForm_MultiFileUploadField(null, this.ViewContext);
        //}

        public PageForm_MultiFileUploadField2 AddMultiFileUpload()
        {
            return new PageForm_MultiFileUploadField2(null,this.ViewContext);
            
        }

        public PageForm_ImageUploadField AddImageUpload()
        {
            return new PageForm_ImageUploadField(null, this.ViewContext);
        }

        //public PageForm_MultiImageUploadField2 AddMultiImageUploader()
        //{
        //    return new PageForm_MultiImageUploadField2(null,ViewContext);
        //}

        public PageForm_MultiImageUploadField2 AddMultiImageUploader()
        {
            return new PageForm_MultiImageUploadField2(null, this.ViewContext);
        }

        public PageForm_LabelField AddLabel()
        {
            return new PageForm_LabelField(null, this.ViewContext);
        }

        public PageForm_RadioListField AddRadioList()
        {
            return new PageForm_RadioListField(null, this.ViewContext);
        }

        public PageForm_SelectorField AddSelector()
        {
            return new PageForm_SelectorField(null, this.ViewContext);
        }

        public PageForm_TextareaField AddTextarea()
        {
            return new PageForm_TextareaField(null, this.ViewContext);
        }

        public PageForm_TextBoxField AddTextBox()
        {
            return new PageForm_TextBoxField(null, this.ViewContext);
        }

        public PageForm_TextBoxWithButton AddTextBoxWithButton()
        {
            return new PageForm_TextBoxWithButton(null, this.ViewContext);
        }

        public PageForm_ValueRangeField AddValueRange()
        {
            return new PageForm_ValueRangeField(null, this.ViewContext);
        }

        public PageForm_CityPicker AddCityPicker()
        {
            return new PageForm_CityPicker(null, this.ViewContext);
        }

        public PageForm_SummerNote AddSummerNote()
        {
            return new PageForm_SummerNote(null, this.ViewContext);
        }

        public PageForm_SwitchField AddSwitchButton()
        {
            return new PageForm_SwitchField(null, this.ViewContext);
        }

        public PageForm_TreeViewSelector AddTreeViewSelector()
        {
            return new PageForm_TreeViewSelector(null, this.ViewContext);
        }

        public PageForm_ButtonList AddButtonList() => new PageForm_ButtonList(null, this.ViewContext);

        public PageForm_FieldsGroup AddFieldGroup() => new PageForm_FieldsGroup(this.ViewContext);

        public ViewContext ViewContext { get; }
    }
}
